package com.example.jwt.controller;

import cn.hutool.core.util.StrUtil;
import com.example.jwt.util.JwtTokenUtil;
import org.springframework.security.access.annotation.Secured;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@RestController
public class TestController {

    @GetMapping("/system/refreshToken")
    public void refreshToken(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String token = StrUtil.removePrefix(request.getHeader("Authorization"), "Bearer").trim();

        response.setHeader("Content-Type", "application/json;charset=utf-8");
        if (JwtTokenUtil.canRefresh(token)) {
            String newToken = JwtTokenUtil.refreshToken(token);
            response.setHeader("Authorization", newToken);
            PrintWriter out = response.getWriter();
            out.write("token刷新成功");
            out.flush();
        }

        PrintWriter out = response.getWriter();
        out.write("token刷新失败");
        out.flush();
    }

    @GetMapping("/anonymous")
    public String anonymous(){
        return "匿名访问";
    }

    @GetMapping("/hello")
    public String hello() {
        return "hello";
    }

    @GetMapping("/bm")
    public String bm() {
        return "访问成功 ,只有boss角色才能访问";
    }

    @GetMapping("/ry")
    public String ry() {
        return "访问成功 ，只有 manager 或者 director 才能访问";
    }


    @GetMapping("/ry/view")
    public String ryView() {
        return "所有人都可以访问";
    }

    // 注解测试
    @Secured("ROLE_boss")
    @GetMapping("/anno/boss")
    public String boss() {
        return "boss";
    }

}
